# -*- coding:utf-8 -*-

__author__='zhaoxp'

import numpy as np
import matplotlib.pyplot as plt
#import matplotlib.pylib  as pylib

from mpl_toolkits.mplot3d import Axes3D


'''how to use matplotlib.pyplot

ref to:
http://old.sebug.net/paper/books/scipydoc/matplotlib_intro.html
http://liam0205.me/2014/09/11/matplotlib-tutorial-zh-cn/


'''

def draw_chart_x():
    x = np.linspace(0, 10, 1000)
    y = np.sin(x)
    z = np.cos(x**2)
    #print x
    #print y
    #print z

    plt.figure(figsize=(8,4 ))
    plt.plot(x, y, label="$sin(x)$", color='red', linewidth=2)
    plt.plot(x, z, 'b--', label='$cos(x^2)$')
    plt.xlabel('Time(s)')
    plt.ylabel('Volt')
    plt.title('PyPlot First Example')
    plt.ylim(-1.2, 1.2)
    plt.legend()
    plt.show()


def draw_chart_simple():
    X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
    C,S = np.cos(X), np.sin(X)
    print X
    plt.plot(X, C)
    plt.plot(X, S)
    plt.show()

def draw_chart_detail():
    plt.figure(figsize=(8, 6), dpi=80)
    plt.subplot(1, 1, 1)
    X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
    C, S = np.cos(X), np.sin(X)
    plt.plot(X, C, color='blue', linewidth=2.0, linestyle='-', label='cosine')#线条的颜色和粗细,图例
    plt.plot(X, S, color='red', linewidth=2.0, linestyle='-', label='sine')#线条的颜色和粗细,图例
    #plt.xlim(-4.0, 4.0)
    plt.xlim(X.min()*1.1, X.max()*1.1)#设置图片边界
    #plt.xticks(np.linspace(-4, 4, 9, endpoint=True))
    plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], 
                [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$'])#设置记号,设置记号的标签
    #plt.ylim(-1.0, 1.0)
    plt.ylim(C.min()*1.1, C.max()*1.1)#设置图片边界
    #plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
    plt.yticks([-1, 0, 1], [r'$-1$', r'$0$', r'$+1$'])#设置记号,设置记号的标签

    #移动脊柱
    ax = plt.gca()
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data',0))
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('data',0))

    #给一些特殊点做注释. 在 2π/32π/3 的位置给两条函数曲线加上一个注释
    #首先，我们在对应的函数图像位置上画一个点；然后，向横轴引一条垂线，以虚线标记；最后，写上标签。
    t = 2*np.pi/3
    plt.plot([t, t],[0, np.cos(t)], color='blue', linewidth=2.5, linestyle='--')
    plt.scatter([t,], [np.cos(t),], 50, color='blue')
    plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
            xy=(t, np.sin(t)), xycoords='data',
            xytext=(+10, +30), textcoords='offset points', fontsize=16,
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    plt.plot([t, t], [0, np.sin(t)], color='red', linewidth=2.5, linestyle='--')
    plt.scatter([t,], [np.sin(t),], 50, color='red')
    plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
            xy=(t, np.cos(t)), xycoords='data',
            xytext=(-90, -50), textcoords='offset points', fontsize=16,
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

    #精益求精
    #坐标轴上的记号标签被曲线挡住了，作为强迫症患者（雾）这是不能忍的。我们可以把它们放大，然后添加一个白色的半透明底色。这样可以保证标签和曲线同时可见。
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(16)
        label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))

    plt.legend(loc='upper left') #图例

    plt.show()


def draw_chart_normal():
    n = 256
    X = np.linspace(-np.pi, np.pi, n ,endpoint=True)
    Y = np.sin(2*X)
    plt.plot(X, Y+1, color='blue', alpha=1.00)
    plt.plot(X, Y-1, color='blue', alpha=1.00)
    plt.show()


def draw_chart_scatter_points():
    n = 1024
    X = np.random.normal(0, 1, n)
    Y = np.random.normal(0, 1, n)
    plt.scatter(X, Y)
    plt.show()


def draw_chart_bar():
    n = 12
    X = np.arange(n)
    Y1 = (1-X/float(n)) * np.random.uniform(0.5, 1.0, n)
    Y2 = (1-X/float(n)) * np.random.uniform(0.5, 1.0, n)
    plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
    plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
    for x, y in zip(X, Y1):
        plt.text(x+0.4, y+0.05, '%.2f'%y, ha='center', va='bottom')
    plt.ylim(-1.25, +1.25)
    plt.show()


def draw_chart_contour():
    '''等高线图
    '''
    n = 256
    x = np.linspace(-3, 3, n)
    y = np.linspace(-3, 3, n)
    def f(x, y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
    X,Y = np.meshgrid(x, y)
    plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet')
    C = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5)
    plt.show()


def draw_chart_grayscale():
    '''灰度图（Imshow）
    n = 10
    def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
    x = np.linspace(-3, 3, 4*n)
    y = np.linspace(-3, 3, 3*n)
    X, Y = np.meshgrid(x, y)
    plt.imshow(f(X, Y))
    '''
    n = 10
    x = np.linspace(-3,3,3.5*n)
    y = np.linspace(-3,3,3.0*n)
    X,Y = np.meshgrid(x,y)
    Z = f(X,Y)

    plt.axes([0.025,0.025,0.95,0.95])
    plt.imshow(Z,interpolation='nearest', cmap='bone', origin='lower')
    plt.colorbar(shrink=.92)

    plt.xticks([]), plt.yticks([])
    plt.show()


def draw_chart_pie():
    '''饼状图
    '''
    n = 20
    Z = np.ones(n)
    Z[-1] *= 2

    plt.axes([0.025,0.025,0.95,0.95])

    plt.pie(Z, explode=Z*.05, colors = ['%f' % (i/float(n)) for i in range(n)])
    plt.gca().set_aspect('equal')
    plt.xticks([]), plt.yticks([])
    plt.show()

def draw_chart_quiver():
    '''量场图（Quiver Plots）
    '''
    n = 8
    X,Y = np.mgrid[0:n,0:n]
    T = np.arctan2(Y-n/2.0, X-n/2.0)
    R = 10+np.sqrt((Y-n/2.0)**2+(X-n/2.0)**2)
    U,V = R*np.cos(T), R*np.sin(T)

    plt.axes([0.025,0.025,0.95,0.95])
    plt.quiver(X,Y,U,V,R, alpha=.5)
    plt.quiver(X,Y,U,V, edgecolor='k', facecolor='None', linewidth=.5)

    plt.xlim(-1,n), plt.xticks([])
    plt.ylim(-1,n), plt.yticks([])
    plt.show()


def draw_chart_grid():
    '''网格
    '''
    ax = plt.axes([0.025,0.025,0.95,0.95])

    ax.set_xlim(0,4)
    ax.set_ylim(0,3)
    ax.xaxis.set_major_locator(plt.MultipleLocator(1.0))
    ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
    ax.yaxis.set_major_locator(plt.MultipleLocator(1.0))
    ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75')
    ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')
    ax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75')
    ax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75')
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    plt.show()


def draw_chart_multi_grid():
    '''多重网格
    '''
    fig = plt.figure()
    fig.subplots_adjust(bottom=0.025, left=0.025, top = 0.975, right=0.975)

    plt.subplot(2,1,1)
    plt.xticks([]), plt.yticks([])

    plt.subplot(2,3,4)
    plt.xticks([]), plt.yticks([])

    plt.subplot(2,3,5)
    plt.xticks([]), plt.yticks([])

    plt.subplot(2,3,6)
    plt.xticks([]), plt.yticks([])
    plt.show()


def draw_chart_polar():
    '''极轴图
    '''
    #ax = plt.axes([0, 0, 1, 1])
    ax = plt.axes([0.025,0.025,0.95,0.95], polar=True)
    N = 20
    theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
    print theta
    radii = 10 * np.random.rand(N)
    width = np.pi / 4 * np.random.rand(N)
    bars = plt.bar(theta, radii, width=width, bottom=0.0)
    for r, bar in zip(radii, bars):
        bar.set_facecolor( plt.cm.jet(r/10.))
        bar.set_alpha(0.5)
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    plt.show()


def draw_chart_3D():
    '''3D图
    '''
    fig = plt.figure()
    ax = Axes3D(fig)
    X = np.arange(-4, 4, 0.25)
    Y = np.arange(-4, 4, 0.25)
    X, Y = np.meshgrid(X, Y)
    R = np.sqrt(X**2, Y**2)
    Z = np.sin(R)
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')
    ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot)
    ax.set_zlim(-2,2)
    plt.show()


def draw_chart_manual_draft():
    '''手稿
    '''
    eqs = []
    eqs.append((r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$"))
    eqs.append((r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$"))
    eqs.append((r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$"))
    eqs.append((r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$"))
    eqs.append((r"$F_G = G\frac{m_1m_2}{r^2}$"))


    plt.axes([0.025,0.025,0.95,0.95])

    for i in range(24):
        index = np.random.randint(0,len(eqs))
        eq = eqs[index]
        size = np.random.uniform(12,32)
        x,y = np.random.uniform(0,1,2)
        alpha = np.random.uniform(0.25,.75)
        plt.text(x, y, eq, ha='center', va='center', color="#11557c", alpha=alpha,
                 transform=plt.gca().transAxes, fontsize=size, clip_on=True)

    plt.xticks([]), plt.yticks([])
    # savefig('../figures/text_ex.png',dpi=48)
    plt.show()


if __name__ == '__main__':
    #draw_chart_simple()
    #draw_chart_detail()
    #draw_chart_x()
    #draw_chart_normal()
    #draw_chart_scatter_points()
    #draw_chart_bar()
    #draw_chart_contour()
    #draw_chart_grayscale()
    #draw_chart_pie()
    draw_chart_quiver()
    #draw_chart_grid()
    #draw_chart_multi_grid()
    #draw_chart_polar()
    #draw_chart_3D()
    #draw_chart_manual_draft()
    pass